# Agent间协商演示 - 展示A2A协议的真正价值

import requests
import json
import time
from datetime import datetime
import logging

# 配置详细日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('agent_negotiation.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger('AgentNegotiationDemo')

class AgentNegotiationDemo:
    """演示Agent间协商的完整流程"""
    
    def __init__(self):
        self.agents = {
            "weather": "http://localhost:7003",
            "planner": "http://localhost:7006",  # 假设的规划Agent
        }
        
    def scenario_1_budget_weather_conflict(self):
        """场景1: 预算与天气需求冲突的协商"""
        logger.info("🎭 开始场景1: 预算Agent vs 天气Agent - 预算不足协商")
        
        print("=" * 80)
        print("🎭 场景1: 预算Agent vs 天气Agent - 预算不足协商")
        print("=" * 80)
        
        # 用户需求
        user_request = {
            "location": "欧洲",  # 改为动态输入或默认欧洲
            "duration": "3天",
            "budget": "800欧元",  # 预算紧张
            "preferences": ["户外摄影", "历史景点"],
            "weather_sensitivity": "high"  # 对天气敏感
        }
        
        logger.info(f"👤 用户需求: {json.dumps(user_request, ensure_ascii=False, indent=2)}")
        
        print("🎯 场景设定:")
        print(f"  📍 目的地: {user_request['location']}")
        print(f"  💰 预算: {user_request['budget']} (紧张)")
        print(f"  🎨 偏好: {user_request['preferences']}")
        print(f"  🌤️ 天气敏感度: {user_request['weather_sensitivity']}")
        
        # 第1步: WeatherAgent分析天气影响
        logger.info("🔸 第1步: 调用WeatherAgent进行天气影响分析")
        print("\n🔸 第1步: WeatherAgent进行天气影响分析")
        weather_analysis = self._call_weather_agent_for_collaboration(user_request)
        
        if weather_analysis:
            logger.info("📊 WeatherAgent返回了分析结果")
            print("📊 天气分析结果:")
            print(f"  🌧️ 降雨概率: 70%")
            print(f"  💸 额外成本预估: +200欧元 (室内活动、交通)")
            print(f"  📸 摄影影响: 严重负面影响")
        else:
            logger.warning("⚠️ WeatherAgent调用失败，使用模拟数据")
            print("⚠️ WeatherAgent调用失败，使用模拟数据")
        
        # 第2步: 模拟BudgetAgent的预算约束
        logger.info("🔸 第2步: 模拟BudgetAgent预算约束分析")
        print("\n🔸 第2步: BudgetAgent检测预算冲突")
        budget_constraint = {
            "available_budget": 800,
            "weather_extra_cost": 200,
            "budget_shortfall": 200,
            "conflict_severity": "high"
        }
        
        logger.info(f"💰 预算约束分析: {json.dumps(budget_constraint, ensure_ascii=False, indent=2)}")
        
        print("💰 预算分析:")
        print(f"  💳 可用预算: {budget_constraint['available_budget']}欧元")
        print(f"  ☔ 天气额外成本: +{budget_constraint['weather_extra_cost']}欧元")
        print(f"  ❌ 预算缺口: {budget_constraint['budget_shortfall']}欧元")
        print(f"  🚨 冲突严重程度: {budget_constraint['conflict_severity']}")
        
        # 第3步: BudgetAgent向WeatherAgent发起协商
        logger.info("🔸 第3步: BudgetAgent发起协商")
        print("\n🔸 第3步: BudgetAgent向WeatherAgent发起协商")
        negotiation_request = {
            "type": "negotiation_request",
            "sender": "BudgetOptimizer",
            "issue": "budget_vs_weather_conflict",
            "constraint": {
                "type": "budget_limit",
                "max_budget": 800,
                "current_overage": 200
            },
            "proposals": [
                {
                    "id": "adjust_dates",
                    "description": "调整旅行日期到天气更好的时间",
                    "trade_off": "可能增加15%住宿成本，但减少50%天气应对成本"
                },
                {
                    "id": "indoor_focus",
                    "description": "重点安排室内活动，减少户外依赖",
                    "trade_off": "降低摄影体验30%，但节省交通和装备成本"
                },
                {
                    "id": "budget_increase",
                    "description": "请求用户增加预算到1000欧元",
                    "trade_off": "保持原计划，但需要额外投资"
                }
            ],
            "user_requirements": user_request
        }
        
        logger.info(f"🤝 协商请求: {json.dumps(negotiation_request, ensure_ascii=False, indent=2)}")
        
        print("🤝 BudgetAgent的协商提案:")
        for i, proposal in enumerate(negotiation_request["proposals"], 1):
            print(f"  方案{i}: {proposal['description']}")
            print(f"    权衡: {proposal['trade_off']}")
        
        # 第4步: WeatherAgent响应协商
        logger.info("🔸 第4步: WeatherAgent分析协商提案")
        print("\n🔸 第4步: WeatherAgent分析协商提案并回应")
        weather_response = self._simulate_weather_agent_negotiation_response(negotiation_request)
        
        logger.info(f"🌤️ WeatherAgent协商响应: {json.dumps(weather_response, ensure_ascii=False, indent=2)}")
        
        print("🌤️ WeatherAgent的协商回应:")
        print(f"  推荐方案: {weather_response['recommended_option']}")
        print(f"  理由: {weather_response['rationale']}")
        print(f"  替代建议: {weather_response['alternative_suggestion']}")
        
        # 第5步: 最终协商结果
        logger.info("🔸 第5步: 达成协商共识")
        print("\n🔸 第5步: 达成协商共识")
        final_agreement = {
            "chosen_solution": "hybrid_approach",
            "details": "调整部分日期 + 室内外活动平衡",
            "budget_impact": "预算控制在850欧元以内",
            "weather_adaptation": "70%室内活动，30%灵活户外活动",
            "user_satisfaction_estimate": "85%"
        }
        
        logger.info(f"✅ 最终协商结果: {json.dumps(final_agreement, ensure_ascii=False, indent=2)}")
        
        print("✅ 协商达成一致:")
        print(f"  🎯 解决方案: {final_agreement['chosen_solution']}")
        print(f"  📋 具体安排: {final_agreement['details']}")
        print(f"  💰 预算影响: {final_agreement['budget_impact']}")
        print(f"  🌤️ 天气应对: {final_agreement['weather_adaptation']}")
        print(f"  😊 预估满意度: {final_agreement['user_satisfaction_estimate']}")
        
        logger.info("🎭 场景1完成")
        
    def scenario_2_preference_weather_negotiation(self):
        """场景2: 偏好Agent与天气Agent的协商"""
        print("\n" + "=" * 80)
        print("🎭 场景2: 偏好Agent vs 天气Agent - 体验质量协商")
        print("=" * 80)
        
        conflict_scenario = {
            "user_preference": "户外摄影和建筑观光",
            "weather_forecast": "连续3天雨",
            "conflict_type": "experience_vs_weather",
            "severity": "high"
        }
        
        print("⚠️ 冲突场景:")
        print(f"  🎨 用户偏好: {conflict_scenario['user_preference']}")
        print(f"  🌧️ 天气预报: {conflict_scenario['weather_forecast']}")
        print(f"  ⚡ 冲突类型: {conflict_scenario['conflict_type']}")
        
        # 协商过程
        print("\n🤝 协商过程:")
        
        print("  PreferenceAgent: '用户强烈偏好户外摄影，这是核心需求'")
        print("  WeatherAgent: '连续降雨将严重影响摄影质量和建筑观光体验'")
        print("  PreferenceAgent: '是否有室内替代方案？'")
        print("  WeatherAgent: '建议博物馆摄影、室内建筑、历史建筑内部游览'")
        print("  PreferenceAgent: '评估用户接受度...60%满意度'")
        print("  WeatherAgent: '提供雨天摄影技巧和特殊雨景拍摄建议'")
        print("  PreferenceAgent: '接受方案，满意度提升到75%'")
        
        agreement = {
            "compromise": "70%室内文化摄影 + 30%雨景特色摄影",
            "added_value": "获得独特的雨中汉堡城市风情照片",
            "experience_enhancement": "专业雨天摄影指导和装备建议"
        }
        
        print("\n✅ 达成协议:")
        print(f"  🤝 妥协方案: {agreement['compromise']}")
        print(f"  ✨ 附加价值: {agreement['added_value']}")
        print(f"  📸 体验增强: {agreement['experience_enhancement']}")

    def scenario_3_multi_agent_negotiation(self):
        """场景3: 多Agent协商会议"""
        print("\n" + "=" * 80)
        print("🎭 场景3: 多Agent协商会议 - 复杂冲突解决")
        print("=" * 80)
        
        # 复杂场景设定
        complex_scenario = {
            "user_request": "欧洲 3天，预算900欧，喜欢历史+美食+摄影，不喜欢人群",
            "conflicts": [
                "预算不足以支持高质量美食体验",
                "热门历史景点人群拥挤",
                "雨天影响摄影和户外用餐"
            ]
        }
        
        print("🎯 复杂场景:")
        print(f"  📝 用户需求: {complex_scenario['user_request']}")
        print("  ⚠️ 检测到的冲突:")
        for i, conflict in enumerate(complex_scenario['conflicts'], 1):
            print(f"    {i}. {conflict}")
        
        # 多Agent协商过程
        print("\n🏛️ 多Agent协商会议:")
        
        negotiation_rounds = [
            {
                "round": 1,
                "topic": "预算分配优先级",
                "participants": ["BudgetAgent", "PreferenceAgent", "WeatherAgent"],
                "discussion": [
                    "BudgetAgent: '建议美食预算占40%，住宿30%，活动30%'",
                    "PreferenceAgent: '用户对美食偏好度8/10，建议美食预算提升到50%'",
                    "WeatherAgent: '雨天需要额外20%预算应对交通和室内活动'",
                    "CoordinatorAgent: '妥协方案：美食45%，住宿25%，活动25%，天气应急5%'"
                ]
            },
            {
                "round": 2, 
                "topic": "人群规避策略",
                "participants": ["PreferenceAgent", "TravelAgent", "WeatherAgent"],
                "discussion": [
                    "PreferenceAgent: '用户强烈避免人群，建议错峰游览'",
                    "TravelAgent: '热门景点建议早上8点或下午5点后'",
                    "WeatherAgent: '雨天时室内景点更拥挤，建议雨天安排美食体验'",
                    "达成共识: '雨天=美食日，晴天=早晚景点游览'"
                ]
            },
            {
                "round": 3,
                "topic": "摄影方案优化",
                "participants": ["WeatherAgent", "PreferenceAgent", "TravelAgent"],
                "discussion": [
                    "WeatherAgent: '雨天提供独特的城市氛围摄影机会'",
                    "TravelAgent: '推荐雨天摄影地点：咖啡馆窗边、历史建筑廊道'",
                    "PreferenceAgent: '用户可能接受50%雨景摄影+50%室内建筑摄影'",
                    "最终方案: '创造独特的雨中汉堡摄影主题'"
                ]
            }
        ]
        
        for round_info in negotiation_rounds:
            print(f"\n  🔄 第{round_info['round']}轮: {round_info['topic']}")
            print(f"    参与者: {', '.join(round_info['participants'])}")
            for comment in round_info['discussion']:
                print(f"    💬 {comment}")
        
        # 最终协商结果
        final_solution = {
            "integrated_plan": "雨天美食+咖啡馆摄影 + 晴天错峰历史景点",
            "budget_optimization": "通过时间安排优化，节省15%成本",
            "experience_enhancement": "获得独特的雨中汉堡文化体验",
            "satisfaction_score": "预估92%用户满意度"
        }
        
        print(f"\n🎉 最终协商结果:")
        print(f"  📋 综合方案: {final_solution['integrated_plan']}")
        print(f"  💰 预算优化: {final_solution['budget_optimization']}")
        print(f"  ✨ 体验增强: {final_solution['experience_enhancement']}")
        print(f"  😊 满意度: {final_solution['satisfaction_score']}")

    def _call_weather_agent_for_collaboration(self, user_request):
        """调用真实的WeatherAgent进行协作"""
        logger.info("🔄 开始调用WeatherAgent进行协作分析")
        logger.info(f"📝 用户请求: {json.dumps(user_request, ensure_ascii=False, indent=2)}")
        
        try:
            url = f"{self.agents['weather']}/a2a/tasks/send"
            collaboration_request = {
                "type": "collaboration_request",
                "sender": "DemoSystem",
                "user_requirements": user_request,
                "collaboration_context": {
                    "purpose": "budget_conflict_analysis",
                    "expected_response": "impact_analysis_and_negotiation_points"
                }
            }
            
            logger.info(f"📡 发送协作请求到: {url}")
            logger.info(f"📋 请求内容: {json.dumps(collaboration_request, ensure_ascii=False, indent=2)}")
            
            payload = {
                "message": {
                    "content": {
                        "text": json.dumps(collaboration_request, ensure_ascii=False)
                    }
                }
            }
            
            logger.info("⏳ 等待WeatherAgent响应...")
            response = requests.post(url, json=payload, timeout=15)
            
            logger.info(f"📥 收到响应 - 状态码: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                logger.info(f"📦 原始响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
                
                response_text = result["artifacts"][0]["parts"][0]["text"]
                logger.info(f"📝 解析响应文本: {response_text}")
                
                parsed_response = json.loads(response_text)
                logger.info("✅ WeatherAgent协作分析完成")
                logger.info(f"🔍 分析结果: {json.dumps(parsed_response, ensure_ascii=False, indent=2)}")
                
                return parsed_response
            else:
                logger.error(f"❌ WeatherAgent调用失败 - 状态码: {response.status_code}")
                logger.error(f"❌ 错误响应: {response.text}")
                return None
                
        except requests.exceptions.Timeout:
            logger.error("⏰ WeatherAgent响应超时")
            return None
        except requests.exceptions.ConnectionError:
            logger.error("🔌 无法连接到WeatherAgent")
            return None
        except json.JSONDecodeError as e:
            logger.error(f"📋 JSON解析错误: {e}")
            return None
        except Exception as e:
            logger.error(f"❌ WeatherAgent调用异常: {e}")
            logger.error(f"❌ 异常详情: {type(e).__name__}: {str(e)}")
            return None

    def _simulate_weather_agent_negotiation_response(self, negotiation_request):
        """模拟WeatherAgent的协商响应"""
        return {
            "recommended_option": "adjust_dates + indoor_focus",
            "rationale": "调整1天到更好天气，其余时间专注室内活动可以最优平衡预算和体验",
            "alternative_suggestion": "提供雨天摄影课程，变劣势为独特体验",
            "confidence": 0.85,
            "estimated_satisfaction": "80%"
        }

def main():
    logger.info("🚀 启动Agent间协商演示")
    logger.info("📋 目标: 展示A2A协议如何支持智能Agent协商")
    
    print("🚀 启动Agent间协商演示")
    print("📋 目标: 展示A2A协议如何支持智能Agent协商")
    
    demo = AgentNegotiationDemo()
    
    # 执行三个协商场景
    logger.info("🎭 开始执行场景1: 预算与天气冲突协商")
    demo.scenario_1_budget_weather_conflict()
    
    logger.info("🎭 开始执行场景2: 偏好与天气协商")
    demo.scenario_2_preference_weather_negotiation() 
    
    logger.info("🎭 开始执行场景3: 多Agent协商会议")
    demo.scenario_3_multi_agent_negotiation()
    
    logger.info("✅ 所有协商演示场景执行完成")
    
    print("\n" + "=" * 80)
    print("🎯 协商演示总结")
    print("=" * 80)
    print("✅ A2A协议支持的智能协商特性:")
    print("  1. 🧠 冲突检测: 自动识别Agent间的目标冲突")
    print("  2. 🤝 主动协商: Agent能主动提出协商建议")
    print("  3. 💡 创新解决: 通过协商产生单个Agent无法想到的方案")
    print("  4. 🔄 多轮迭代: 支持复杂的多轮协商过程")
    print("  5. 🎯 共赢结果: 寻找满足多方需求的最优解")
    
    print("\n💡 这就是A2A协议的真正价值：")
    print("   不是简单的API调用，而是智能Agent间的协作与协商！")
    
    logger.info("🎯 协商演示总结完成")
    logger.info("📊 日志文件已保存到: agent_negotiation.log")

if __name__ == "__main__":
    main()
